<template>
	<view class="z-upload-image" :class="'z-upload-image_' + mode">
    <!-- 已上传预览 -->
    <view class="z-image-item z-image-item_image" v-for="(img, i) in tempFileList" :key="i">
      <view class="z-image-item__wrapper">
        <view class="z-image-item__content">
          <image class="image" :src="img.path" mode=""></image>
          <view v-show="showClose" class="close" @click="onRemove(img.uid)">
            <uni-icons type="closeempty" size="28rpx" color="#fff"></uni-icons>
          </view>

          <!-- 加载效果 -->
          <view class="loading" v-if="img.status === 'uploading'">
            <z-upload-loading />
          </view>
        </view>
      </view>
    </view>

    <!-- 上传按钮 -->
    <view class="z-image-item z-image-item_add" @click="onSelect" v-if="!disabled && tempFileList.length < limit">
		<template v-if="actionType === 'default'">
			<view class="z-image-item__wrapper">
			  <view class="z-image-item__content">
				  <view class="btn">
					  <image class="btn_icon" src="http://www.xvopen.com/xiaoV/img1/camera.png"></image>
					  <text class="btn_text">{{ text }}</text>
					</view>
			  </view>
			</view>
		</template>
		<template v-else>
			<slot></slot>
		</template>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'
import { uploadFiles } from '@/api/index.js'
import zUploadLoading from './z-upload-loading'

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  limit: {
    type: [String, Number],
    default: '9'
  },
  mode: {
    type: String,
    default: 'grid'
  },
  auto: {
    type: Boolean,
    default: true
  },
  files: {
    type: String,
    default: ''
  },
  text: {
    type: String,
    default: '添加图片'
  },
  actionType: {
	  type: String,
    default: 'default'
  },
  showClose: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits(['update:files'])

const tempFileList = ref([])
let fileList = []
let uid = 0
let sendCount = 0

watch(() => props.files, newV => {
	// console.log(newV,'newV')
  if(sendCount > 0) {
    sendCount--
    return
  }
  if(newV) {
    const paths = newV.split(',')
    const _temp = paths.map(path => {
      uid++
      return { path, uid, status: 'success' }
    })
    const _files = paths.map(path => ({ path, uid }))
    tempFileList.value = _temp
    fileList = _files
  } else {
    if (tempFileList.value.length) tempFileList.value = []
    if (fileList.length) fileList = []
  }
}, { immediate: true })


const onRemove = (uid) => {
  updateFileList(uid, 'remove')
  sendFileList()
}

const uploadImage = async ({name, filePath, uid}) => {

  const { url } = await uploadFiles({ file: filePath })
  console.log(filePath,'url')
  if ( url) {
    updateFileList(uid, 'update', url)
  } else {
    updateFileList(uid, 'remove')
  }
  sendFileList()
}

const sendFileList = () => {
  const result = fileList.filter(({ path }) => path).map(({ path }) => path).join(',')
  sendCount++
  emits('update:files', result)
}

const onSelect = async () => {
  const { limit } = props
  const result = await uni.chooseImage({ count: Number(limit), sourceType: ['album'] }).catch(() => ({}))
  const { tempFilePaths, tempFiles } = result
  if (tempFilePaths) {
    const len = tempFileList.value.length
    let count = limit - len
    if (count < 0) count = 0
    const paths = tempFilePaths.slice(0, count)
    paths.forEach((path, index) => {
      uid++
      tempFileList.value.push({ path, uid, status: 'uploading' })
      fileList.push({ uid })
      const { name } = tempFiles[index]
      uploadImage({ name, filePath: path, uid })
    })
  }
}

const updateFileList = (uid, action, args) => {
  const tempIndex = tempFileList.value.findIndex((v) => v.uid === uid)
  const index = fileList.findIndex((v) => v.uid === uid)
  switch (action) {
    case 'update':
      if (tempIndex > -1) {
        setTimeout(() => {
          tempFileList.value[tempIndex].status = 'success'
        }, 1000)
      }
      if (index > -1) fileList[index].path = args
      break
    case 'remove':
      tempFileList.value.splice(tempIndex, 1)
      fileList.splice(index, 1)
      break
  }
}
</script>

<style lang="scss">
.z-upload-image_grid {
  position: relative;
  display: flex;
  height: 100%;
  .z-image-item {
    width: 100%;
    height: 100%;
    position: relative;

    .z-image-item__wrapper {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

    .z-image-item__content {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
      overflow: hidden;
      z-index: 1;
      background-color: #f6f9f8;
      position: relative;
    }
  }

  .z-image-item_image {
    .image {
      width: 100%;
      height: 100%;
    }

    .close {
      position: absolute;
      top: 0;
      right: 0;
      width: 40rpx;
      height: 40rpx;
      display: flex;
	  justify-content: center;
	  align-items: center;
      background-color: rgba(0, 0, 0, 0.7);
      border-radius: 0 16rpx 0 16rpx;
    }

    .loading{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 2;
    }
  }

  .z-image-item_add {
    .btn {
		display: flex;
	  justify-content: center;
	  align-items: center;
      width: 100%;
      height: 100%;

      .btn_icon {
        width: 60rpx;
        height: 52rpx;
      }

      .btn_text {
        margin-top: 20rpx;
        font-size: 26rpx;
        color: #898989;
      }
    }
  }
}
</style>
